package com.charity.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.charity.domain.CharityBox;
import com.charity.mapper.CharityBoxMapper;
import com.charity.service.ICharityBoxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Primary
public class CharityBoxServiceImpl implements ICharityBoxService {

    @Autowired
    private CharityBoxMapper charityBoxMapper;


    @Override
    @Transactional
    public boolean createCharityBox(CharityBox charityBox) {
        try {
            charityBoxMapper.insert(charityBox);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateCharityBox(CharityBox charityBox) {
        try {
            if (!charityBoxMapper.existsById(charityBox.getId())) {
                return false;
            }
            charityBoxMapper.updateById(charityBox);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deleteCharityBox(Long boxId) {
        try {
            if (!charityBoxMapper.existsById(boxId)) {
                return false;
            }
            charityBoxMapper.deleteById(boxId);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Page<CharityBox> getCharityBoxList(Integer status, int pageNum, int pageSize) {
        Page<CharityBox> page = new Page<>(pageNum, pageSize);
        if (status != null) {
            return charityBoxMapper.selectByStatus(status, page);
        }
        return charityBoxMapper.selectAll(page);
    }


    @Override
    @Transactional
    public boolean updateBoxStatus(Long boxId, Integer status) {
        try {
            CharityBox charityBox = charityBoxMapper.selectById(boxId);
            if (charityBox == null) {
                return false;
            }
            charityBox.setStatus(status);
            charityBoxMapper.updateById(charityBox);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}